package netty.coffee;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * 咖啡机设备模拟器
 *
 * @Author zhangtao
 * @create 2021/11/2 9:19
 */
@Slf4j
public class CoffeeMonitor {
    private String ip;
    private int port;

    public CoffeeMonitor(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public void monitor() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        Bootstrap bs = new Bootstrap();
        bs.group(bossGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new CoffeeEncoder());
                        // 处理来自服务端的响应信息
                        socketChannel.pipeline().addLast(new CoffeeDataHandler());
                    }
                });

        ChannelFuture cf = bs.connect(ip, port).sync();
        // 等待直到连接中断
        cf.channel().closeFuture().sync();
    }

    public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException {
        new CoffeeMonitor("127.0.0.1", 40002).monitor();
    }
}
